package com.payment.controller.queryresult;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.payment.entity.common.UserOrderPackage;
import com.payment.entity.payment.wxquery.request.RequestWeiXinQueryOrder;
import com.payment.entity.payment.wxquery.request.RequestWeiXinQueryOrderData;
import com.payment.entity.payment.wxquery.request.RequestWeiXinQueryOrderTradeData;
import com.payment.entity.payment.wxquery.response.ResponseWeiXinQueryOrder;
import com.payment.entity.payment.wxquery.response.ResponseWeiXinQueryOrderData;
import com.payment.entity.payment.wxquery.response.ResponseWeiXinQueryOrderTradeData;
import com.payment.service.PartnerPackageService;
import com.payment.service.SequenceService;
import com.payment.service.UserOrderPackageService;
import com.payment.service.UserOrderPaymentService;
import com.payment.utils.MD5;
import com.payment.utils.UtilsInterfacesPackage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Api(description = "查询支付结果")

/**
 * 前端展示支付结果是成功或者失败的接口根据：
 *
 * 1，先请求weixinQuery此接口，得到0000即直接返回支付成功；得到9999即直接返回支付失败；
 *
 * 2，如果上面接口返回的结果是9998：未查询成功支付记录，请稍后再查的提示时；
 *
 * 3，前端直接请求另一个接口：confirmPayResult ;
 *
 * 4,此接口任务完成；
 *
 * @author lm
 * @date 2019/5/24
 */

public class QueryPaymentResultController {

    private static Logger logger = Logger.getLogger(QueryPaymentResultController.class);
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    UserOrderPaymentService paymentService;
    @Autowired
    UserOrderPackageService orderService;
    @Autowired
    PartnerPackageService partnerPackageService;

    /****
     *
     * @param requestWeiXinQueryOrder
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/weixinQuery", produces = "application/json;charset=utf-8")
    @CrossOrigin
    @ResponseBody
    @ApiOperation(value = "查询支付结果", response = ResponseWeiXinQueryOrder.class)
    public String weixinQuery(@ApiParam @RequestBody RequestWeiXinQueryOrder requestWeiXinQueryOrder) throws Exception {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3，定义回报报文
        String jsonString = "";
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestWeiXinQueryOrder);
        if (requestStr == null) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求报文是：" + requestStr);
            RequestWeiXinQueryOrder requestPackage = JSONArray.parseObject(requestStr, RequestWeiXinQueryOrder.class);
            String requestSign = requestPackage.getSign();
            if (requestSign == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestWeiXinQueryOrderData requestData = requestPackage.getData();
                if (requestData == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String version = requestData.getVersion();

                    RequestWeiXinQueryOrderTradeData requestTradeData = requestData.getTradeData();

                    if (StringUtils.isBlank(partnerCode) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || requestTradeData == null || version == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        // 将Str拿去计算签名
                        String signs = utils.calculateSignature(str);
                        logger.info("计算的签名是：" + signs);
                        if (!requestSign.equalsIgnoreCase(signs)) {
                            logger.info("签名验证失败！");
                            jsonString = utils.signatureFailure(ConnSeqNo, partnerCode, tradeTime, tradeType);
                            return jsonString;
                        } else {
                            //这个值是前端不知道的
                            String transaction_id = "";
                            String prePayInfoXml = "";

                            String payType = requestTradeData.getPayType();
                            String out_trade_no = requestTradeData.getPayId();

                            ResponseWeiXinQueryOrderData data = null;

                            if (StringUtils.isNotBlank(payType) && StringUtils.isNotBlank(out_trade_no)) {

                                List<UserOrderPackage> orderPackageList = orderService.getPackageListByOutNo(out_trade_no);

                                if (orderPackageList != null && orderPackageList.size() > 0 && !orderPackageList.isEmpty()) {

                                    List<ResponseWeiXinQueryOrderTradeData> tradeDataList = new ArrayList<ResponseWeiXinQueryOrderTradeData>();
                                    ResponseWeiXinQueryOrderTradeData tradeData = null;

                                    for (UserOrderPackage o : orderPackageList) {

                                        String packageCode = o.getPackageCode();
                                        String packageType = o.getPackageType();
                                        String packageNameEN = partnerPackageService.queryPackageNameEN(partnerCode, packageCode);
                                        String payRst = o.getPayRst();
                                        String deviceCode = o.getDeviceCode();

//                                        if (deviceCode.equals("89852022018041802301")) {
//
//                                            //这张卡模拟支付失败流程：
//                                            data = new ResponseWeiXinQueryOrderData();
//                                            data.setConnSeqNo(ConnSeqNo);
//                                            data.setPartnerCode(partnerCode);
//                                            data.setTradeType(tradeType);
//                                            data.setTradeTime(tradeTime);
//                                            data.setTradeRstCode("9998");
//                                            if (lang.equals("cn")) {
//                                                data.setTradeRstMessage("未查询成功支付记录，请稍后再查！");
//                                            } else {
//                                                data.setTradeRstMessage("Failed to check the successful payment record, please check again later!");
//                                            }
//
//                                        } else {

                                        if (StringUtils.isNotBlank(payRst)) {
                                            //成功
                                            if (payRst.equalsIgnoreCase("success")) {

                                                tradeData = new ResponseWeiXinQueryOrderTradeData();
                                                if (lang.equals("cn")) {
                                                    tradeData.setPackageName(o.getPackageName());
                                                } else {
                                                    tradeData.setPackageName(packageNameEN);
                                                }

                                                if (lang.equalsIgnoreCase("cn")) {

                                                    if (packageType.equals("1") || packageType.equals("0")) {

                                                        tradeData.setOrderPeriod(o.getOrderPeriod() + "天");
                                                    } else if (packageType.equals("2")) {

                                                        tradeData.setOrderPeriod(o.getOrderPeriod() + "个月");
                                                    } else if (packageType.equals("3")) {

                                                        tradeData.setOrderPeriod(Integer.parseInt(o.getOrderPeriod()) * 3 + "个月");

                                                    } else if (packageType.equals("4")) {

                                                        tradeData.setOrderPeriod(Integer.parseInt(o.getOrderPeriod()) * 6 + "个月");

                                                    } else if (packageType.equals("5")) {

                                                        tradeData.setOrderPeriod(o.getOrderPeriod() + "年");
                                                    }

                                                } else {

                                                    if (packageType.equals("1") || packageType.equals("0")) {

                                                        tradeData.setOrderPeriod(o.getOrderPeriod() + "day(s)");
                                                    } else if (packageType.equals("2")) {

                                                        tradeData.setOrderPeriod(o.getOrderPeriod() + "month(s)");
                                                    } else if (packageType.equals("3")) {

                                                        tradeData.setOrderPeriod(Integer.parseInt(o.getOrderPeriod()) * 3 + "month(s)");

                                                    } else if (packageType.equals("4")) {

                                                        tradeData.setOrderPeriod(Integer.parseInt(o.getOrderPeriod()) * 6 + "month(s)");

                                                    } else if (packageType.equals("5")) {

                                                        tradeData.setOrderPeriod(o.getOrderPeriod() + "year(s)");
                                                    }

                                                }
                                                //tradeData.setOrderPeriod(o.getOrderPeriod());
                                                tradeDataList.add(tradeData);

                                                //开始接口返回,将微信返回的结果直接返回
                                                data = new ResponseWeiXinQueryOrderData();
                                                data.setConnSeqNo(ConnSeqNo);
                                                data.setPartnerCode(partnerCode);
                                                data.setTradeType(tradeType);
                                                data.setTradeTime(tradeTime);
                                                data.setPayAmount(o.getPayAmount());
                                                data.setPayCurrency(o.getPayCurrency());

                                                data.setTradeRstCode("0000");
                                                if (lang.equals("cn")) {
                                                    data.setTradeRstMessage("支付成功！");
                                                } else {
                                                    data.setTradeRstMessage("success!");
                                                }
                                                data.setTradeData(tradeDataList);

                                            } else {//失败
                                                data = new ResponseWeiXinQueryOrderData();
                                                data.setConnSeqNo(ConnSeqNo);
                                                data.setPartnerCode(partnerCode);
                                                data.setTradeType(tradeType);
                                                data.setTradeTime(tradeTime);
                                                data.setPayAmount(o.getPayAmount());
                                                data.setPayCurrency(o.getPayCurrency());

                                                data.setTradeRstCode("9999");
                                                if (lang.equals("cn")) {
                                                    data.setTradeRstMessage("支付失败！");
                                                } else {
                                                    data.setTradeRstMessage("fail!");
                                                }

                                            }

                                        } else {//此时有可能是失败----此时就延迟处理

                                            data = new ResponseWeiXinQueryOrderData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(tradeTime);
                                            data.setTradeRstCode("9998");
                                            if (lang.equals("cn")) {
                                                data.setTradeRstMessage("未查询成功支付记录，请稍后再查！");
                                            } else {
                                                data.setTradeRstMessage("Failed to check the successful payment record, please check again later!");
                                            }
                                        }


                                        //}
                                    }

                                } else {
                                    //未查询到当前订单记录

                                    data = new ResponseWeiXinQueryOrderData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(tradeTime);
                                    data.setPayAmount("0");
                                    data.setPayCurrency("CNY");
                                    data.setTradeRstCode("9999");
                                    if (lang.equals("cn")) {
                                        data.setTradeRstMessage("未查询到此订单支付记录!");
                                    } else {
                                        data.setTradeRstMessage("The payment record of this order was not found!");
                                    }

                                }

                                ResponseWeiXinQueryOrder responseOrder = new ResponseWeiXinQueryOrder();
                                responseOrder.setData(data);
                                responseOrder.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                // 返回给调用者的报文
                                jsonString = JSON.toJSONString(responseOrder);
                                logger.info("响应报文：" + jsonString);
                                return jsonString;

                            } else {
                                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                logger.info("响应报文：" + jsonString);
                                return jsonString;
                            }


                        }
                    }
                }
            }
        }
    }

}
